"""
配置面板类，包含各种配置选项
"""
import os
import logging
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, QLabel, 
    QLineEdit, QComboBox, QSlider, QPushButton, QTableWidget,
    QTableWidgetItem, QHeaderView, QCheckBox, QTextEdit, QApplication,
    QFileDialog, QRadioButton, QMessageBox
)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtMultimedia import QAudioDeviceInfo, QAudio
from PyQt5.QtGui import QIntValidator

from app.ui.components.styled_button import StyledButton
from app.ui.components.styled_label import StyledLabel
from app.ui.components.toast import show_toast, Toast
from app.utils.logger import Logger
from app.ui.modules.speech_module import SpeechModule
from app.ui.modules.ai_config_module import AIConfigModule
from app.ui.modules.voice_module import VoiceModule
from app.services.service_locator import ServiceLocator
from app.services.config_service import IConfigService
from app.services.audio_service import IAudioService

class ConfigPanel(QWidget):
    """
    配置面板类，包含各种配置选项
    """
    
    # 定义信号
    config_updated = pyqtSignal(str, object)  # 配置项名称, 值
    
    def __init__(self, parent=None):
        """
        初始化配置面板
        """
        super().__init__(parent)
        
        # 获取日志记录器
        self.logger = Logger.get_logger("config_panel")
        
        # 初始化成员变量
        self.config_path_input = None
        self.audio_output_combo = None
        self.host_speed_value = None
        self.host_speed_slider = None
        self.assist_speed_value = None
        self.assist_speed_slider = None
        self.reverb_value = None
        self.reverb_slider = None
        self.volume_value = None
        self.volume_slider = None
        self.keyword_min_input = None
        self.keyword_max_input = None
        self.user_join_min_input = None
        self.user_join_max_input = None
        self.speech_interval_min_input = None  # 话术间隔最小时间
        self.speech_interval_max_input = None  # 话术间隔最大时间
        self.token_input = None
        self.bot_combo = None
        self.conversation_combo = None
        self.stream_checkbox = None
        self.auto_reply_checkbox = None
        self.auto_speech_checkbox = None
        self.prompt_template = None
        self.host_voice_combo = None
        self.assist_voice_combo = None
        self.keyword_checkbox = None
        self.user_join_checkbox = None
        
        # 流量欢迎配置成员变量
        self.flow_welcome_enabled = None
        self.flow_period_input = None
        self.low_flow_threshold_input = None
        self.high_flow_threshold_input = None
        self.medium_flow_ratio_slider = None
        self.medium_flow_ratio_value = None
        self.trigger_ratio_slider = None
        self.trigger_ratio_value = None
        
        # 初始化模块
        self.speech_module = None
        self.ai_config_module = None
        self.voice_module = None
        
        # 初始化 UI
        self._init_ui()
    
    def _init_ui(self):
        """
        初始化UI
        """
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建左侧配置面板
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        left_layout.setContentsMargins(10, 10, 10, 10)
        left_layout.setSpacing(10)
        
        # 创建音频配置组
        self._create_audio_config_group(left_layout)
        
        # 创建话术来源配置组
        self._create_speech_source_group(left_layout)
        
        # 创建语音配置组（合并音色配置和语速配置）
        self._create_voice_and_speed_config_group(left_layout)
        
        # 创建音频效果组
        self._create_audio_effect_group(left_layout)
        
        # 创建关键词配置组
        self._create_keyword_config_group(left_layout)
        
        # 创建动态流量欢迎配置组
        self._create_flow_welcome_config_group(left_layout)
        
        # 创建AI配置模块
        self.ai_config_module = AIConfigModule()
        self.ai_config_module.ai_config_updated.connect(self._on_ai_config_updated)
        left_layout.addWidget(self.ai_config_module)
        
        # 创建右侧面板
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(10, 10, 10, 10)
        right_layout.setSpacing(10)
        
        # 创建话术管理模块
        self.speech_module = SpeechModule()
        self.speech_module.speech_updated.connect(self._on_speech_updated)
        right_layout.addWidget(self.speech_module)
        
        # 创建分割布局
        splitter_layout = QHBoxLayout()
        splitter_layout.addWidget(left_panel, 1)  # 左侧面板占1份
        splitter_layout.addWidget(right_panel, 1)
        
        main_layout.addLayout(splitter_layout)
    
    def _create_audio_config_group(self, parent_layout):
        """
        创建音频配置组
        
        @param parent_layout: 父布局
        """
        # 创建音频配置组
        audio_group = QGroupBox("音频配置")
        audio_layout = QHBoxLayout(audio_group)  # 使用水平布局
        audio_layout.setContentsMargins(15, 15, 15, 15)  # 设置适当的内边距
        audio_layout.setSpacing(10)  # 设置间距更小
        
        # 配置路径标签
        config_path_label = StyledLabel("配置路径:", size=StyledLabel.SMALL)
        config_path_label.setAlignment(Qt.AlignVCenter)
        
        # 配置路径输入框
        self.config_path_input = QLineEdit()
        self.config_path_input.setReadOnly(True)  # 设置为只读
        self.config_path_input.setMinimumHeight(28)  # 设置最小高度
        
        # 浏览按钮
        browse_button = StyledButton("浏览")
        browse_button.setFixedWidth(60)  # 减小按钮宽度
        browse_button.clicked.connect(self._on_browse_clicked)
        
        # 刷新配置按钮
        refresh_config_button = StyledButton("刷新")
        refresh_config_button.setFixedWidth(60)  # 减小按钮宽度
        refresh_config_button.clicked.connect(self._on_refresh_config_clicked)
        
        # 添加到布局
        audio_layout.addWidget(config_path_label)
        audio_layout.addWidget(self.config_path_input, 1)  # 输入框占据较多空间
        audio_layout.addWidget(browse_button)
        audio_layout.addWidget(refresh_config_button)
        
        parent_layout.addWidget(audio_group)
    
    def _create_speech_source_group(self, parent_layout):
        """
        创建话术来源配置组
        
        @param parent_layout: 父布局
        """
        # 创建话术来源配置组
        speech_source_group = QGroupBox("话术来源配置")
        speech_source_layout = QHBoxLayout(speech_source_group)
        speech_source_layout.setContentsMargins(15, 15, 15, 15)
        speech_source_layout.setSpacing(10)
        
        # 话术来源标签
        source_label = StyledLabel("话术来源:", size=StyledLabel.SMALL)
        source_label.setAlignment(Qt.AlignVCenter)
        speech_source_layout.addWidget(source_label)
        
        # 话术来源下拉框
        self.speech_source_combo = QComboBox()
        self.speech_source_combo.setMinimumHeight(28)
        self.speech_source_combo.currentTextChanged.connect(self._on_speech_source_changed)
        speech_source_layout.addWidget(self.speech_source_combo, 1)
        
        # 刷新按钮
        refresh_btn = StyledButton("刷新")
        refresh_btn.setFixedWidth(60)
        refresh_btn.clicked.connect(self._load_speech_sources)
        speech_source_layout.addWidget(refresh_btn)
        
        parent_layout.addWidget(speech_source_group)
    
    def _create_voice_and_speed_config_group(self, parent_layout):
        """
        创建语音配置组（合并音色配置和语速配置）
        
        @param parent_layout: 父布局
        """
        # 创建语音配置组
        voice_group = QGroupBox("语音配置")
        voice_layout = QVBoxLayout(voice_group)
        voice_layout.setContentsMargins(15, 15, 15, 15)
        
        # 创建音色管理模块（第一行）
        self.voice_module = VoiceModule()
        self.voice_module.voice_updated.connect(self._on_speech_updated)
        voice_layout.addWidget(self.voice_module)
        
        # 添加语速配置（第二行）
        # 主播和助播语速行
        speed_row = QHBoxLayout()
        speed_row.setSpacing(10)  # 减小间距
        
        # 主播语速标签
        host_speed_label = StyledLabel("主播语速:", size=StyledLabel.SMALL)
        host_speed_label.setAlignment(Qt.AlignVCenter)
        
        # 主播语速滑块
        self.host_speed_slider = QSlider(Qt.Horizontal)
        self.host_speed_slider.setRange(30, 200)  # 范围从0.3到2.0，乘以100便于滑块操作
        self.host_speed_slider.setSingleStep(1)  # 设置单步为1，相当于0.01的变化
        self.host_speed_slider.setValue(80)  # 默认值0.8
        self.host_speed_slider.setFixedHeight(20)  # 设置固定高度
        
        # 主播语速值
        self.host_speed_value = StyledLabel("0.8", size=StyledLabel.SMALL)
        self.host_speed_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.host_speed_value.setFixedWidth(30)
        
        # 连接滑块值变化信号
        self.host_speed_slider.valueChanged.connect(self._on_host_speed_changed)
        
        # 助播语速标签
        assist_speed_label = StyledLabel("助播语速:", size=StyledLabel.SMALL)
        assist_speed_label.setAlignment(Qt.AlignVCenter)
        
        # 助播语速滑块
        self.assist_speed_slider = QSlider(Qt.Horizontal)
        self.assist_speed_slider.setRange(30, 200)  # 范围从0.3到2.0，乘以100便于滑块操作
        self.assist_speed_slider.setSingleStep(1)  # 设置单步为1，相当于0.01的变化
        self.assist_speed_slider.setValue(100)  # 默认值1.0
        self.assist_speed_slider.setFixedHeight(20)  # 设置固定高度
        self.assist_speed_slider.setEnabled(False)  # 设置为不可调整，因为助播功能尚未开发
        
        # 助播语速值
        self.assist_speed_value = StyledLabel("1.0", size=StyledLabel.SMALL)
        self.assist_speed_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.assist_speed_value.setFixedWidth(30)
        
        # 连接滑块值变化信号
        self.assist_speed_slider.valueChanged.connect(self._on_assist_speed_changed)
        
        # 添加主播语速到水平布局
        speed_row.addWidget(host_speed_label)
        speed_row.addWidget(self.host_speed_slider, 1)  # 滑块占据剩余空间
        speed_row.addWidget(self.host_speed_value)
        
        # 添加间隔
        speed_row.addSpacing(10)  # 减小间隔
        
        # 添加助播语速到水平布局
        speed_row.addWidget(assist_speed_label)
        speed_row.addWidget(self.assist_speed_slider, 1)  # 滑块占据剩余空间
        speed_row.addWidget(self.assist_speed_value)
        
        # 添加到语音配置布局中
        voice_layout.addLayout(speed_row)
        
        # 添加话术间隔时间配置（第三行）
        interval_row = QHBoxLayout()
        interval_row.setSpacing(10)  # 设置间距更小
        
        # 话术间隔时间标签
        interval_label = StyledLabel("话术间隔:", size=StyledLabel.SMALL)
        interval_label.setAlignment(Qt.AlignVCenter)
        
        # 话术间隔最小时间输入框
        self.speech_interval_min_input = QLineEdit("100")
        self.speech_interval_min_input.setFixedWidth(40)  # 减小宽度
        self.speech_interval_min_input.setMinimumHeight(28)  # 设置最小高度
        self.speech_interval_min_input.setAlignment(Qt.AlignCenter)
        # 设置验证器，只允许输入非负整数
        self.speech_interval_min_input.setValidator(QIntValidator(0, 10000))
        
        # 短横线
        interval_dash_label = StyledLabel("-", size=StyledLabel.SMALL)
        interval_dash_label.setAlignment(Qt.AlignVCenter)
        
        # 话术间隔最大时间输入框
        self.speech_interval_max_input = QLineEdit("1000")
        self.speech_interval_max_input.setFixedWidth(40)  # 减小宽度
        self.speech_interval_max_input.setMinimumHeight(28)  # 设置最小高度
        self.speech_interval_max_input.setAlignment(Qt.AlignCenter)
        # 设置验证器，只允许输入非负整数
        self.speech_interval_max_input.setValidator(QIntValidator(0, 10000))
        
        # 毫秒标签
        interval_ms_label = StyledLabel("毫秒", size=StyledLabel.SMALL)
        interval_ms_label.setAlignment(Qt.AlignVCenter)
        
        # 连接输入框变化事件
        self.speech_interval_min_input.textChanged.connect(self._update_speech_interval_status)
        self.speech_interval_max_input.textChanged.connect(self._update_speech_interval_status)
        
        # 添加到水平布局
        interval_row.addWidget(interval_label)
        interval_row.addWidget(self.speech_interval_min_input)
        interval_row.addWidget(interval_dash_label)
        interval_row.addWidget(self.speech_interval_max_input)
        interval_row.addWidget(interval_ms_label)
        
        # 添加间隔
        interval_row.addSpacing(10)
        
        # 添加音频空白处理选项
        audio_trim_label = StyledLabel("空白处理:", size=StyledLabel.SMALL)
        audio_trim_label.setAlignment(Qt.AlignVCenter)
        
        # 使能选择框
        self.audio_trim_enabled = QCheckBox("启用")
        self.audio_trim_enabled.setChecked(True)
        self.audio_trim_enabled.stateChanged.connect(self._update_audio_trim_status)
        
        # 灵敏度标签
        trim_threshold_label = StyledLabel("灵敏度:", size=StyledLabel.SMALL)
        trim_threshold_label.setAlignment(Qt.AlignVCenter)
        
        # 灵敏度滑块
        self.audio_trim_threshold_slider = QSlider(Qt.Horizontal)
        self.audio_trim_threshold_slider.setRange(10, 50)  # 范围从0.01到0.05
        self.audio_trim_threshold_slider.setValue(20)  # 默认值0.02
        self.audio_trim_threshold_slider.setFixedHeight(20)  # 设置固定高度
        self.audio_trim_threshold_slider.setFixedWidth(80)  # 减小固定宽度
        
        # 灵敏度值标签
        self.audio_trim_threshold_value = StyledLabel("0.02", size=StyledLabel.SMALL)
        self.audio_trim_threshold_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.audio_trim_threshold_value.setFixedWidth(40)
        
        # 连接滑块值变化信号
        self.audio_trim_threshold_slider.valueChanged.connect(self._on_audio_trim_threshold_changed)
        
        # 添加到水平布局
        interval_row.addWidget(audio_trim_label)
        interval_row.addWidget(self.audio_trim_enabled)
        interval_row.addWidget(trim_threshold_label)
        interval_row.addWidget(self.audio_trim_threshold_slider)
        interval_row.addWidget(self.audio_trim_threshold_value)
        
        # 添加足够的空间，使布局与上面的语速行对齐
        interval_row.addStretch(1)
        
        # 添加到语音配置布局中
        voice_layout.addLayout(interval_row)
        
        parent_layout.addWidget(voice_group)
    
    def _create_audio_effect_group(self, parent_layout):
        """
        创建音量配置组
        """
        audio_effect_group = QGroupBox("音量配置")
        audio_effect_layout = QHBoxLayout(audio_effect_group)  # 使用水平布局
        audio_effect_layout.setContentsMargins(15, 15, 15, 15)  # 设置适当的内边距
        audio_effect_layout.setSpacing(10)  # 减小间距
        
        # 音频输出标签
        audio_output_label = StyledLabel("音频输出:", size=StyledLabel.SMALL)
        audio_output_label.setAlignment(Qt.AlignVCenter)
        
        # 音频输出下拉框
        self.audio_output_combo = QComboBox()
        self.audio_output_combo.setMinimumHeight(28)  # 设置最小高度
        
        # 获取系统音频输出设备
        self._load_audio_devices()
        
        self.audio_output_combo.currentTextChanged.connect(self._update_audio_output_status)
        
        # 输出音量标签
        volume_label = StyledLabel("输出音量:", size=StyledLabel.SMALL)
        volume_label.setAlignment(Qt.AlignVCenter)
        
        # 输出音量滑块
        self.volume_slider = QSlider(Qt.Horizontal)
        self.volume_slider.setRange(0, 100)
        self.volume_slider.setValue(80)
        self.volume_slider.setFixedHeight(20)  # 设置固定高度
        
        # 输出音量值
        self.volume_value = StyledLabel("80", size=StyledLabel.SMALL)
        self.volume_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.volume_value.setFixedWidth(30)
        
        # 连接滑块值变化信号
        self.volume_slider.valueChanged.connect(self._on_volume_changed)
        
        # 添加到水平布局
        audio_effect_layout.addWidget(audio_output_label)
        audio_effect_layout.addWidget(self.audio_output_combo, 1)  # 下拉框占更多空间
        audio_effect_layout.addSpacing(10)
        audio_effect_layout.addWidget(volume_label)
        audio_effect_layout.addWidget(self.volume_slider, 1)  # 滑块也占更多空间
        audio_effect_layout.addWidget(self.volume_value)
        
        parent_layout.addWidget(audio_effect_group)
    
    def _create_keyword_config_group(self, parent_layout):
        """
        创建关键词配置组
        """
        keyword_group = QGroupBox("关键词设置")
        keyword_layout = QHBoxLayout(keyword_group)  # 改为水平布局
        keyword_layout.setContentsMargins(15, 15, 15, 15)  # 设置适当的内边距
        keyword_layout.setSpacing(10)  # 设置水平间距
        
        # 关键词设置标签
        keyword_label = StyledLabel("关键词设置:", size=StyledLabel.SMALL)
        keyword_label.setAlignment(Qt.AlignVCenter)
        
        # 关键词设置输入框和控件
        self.keyword_min_input = QLineEdit("30")
        self.keyword_min_input.setFixedWidth(40)  # 缩小输入框宽度
        self.keyword_min_input.setMinimumHeight(28)  # 设置最小高度
        self.keyword_min_input.setAlignment(Qt.AlignCenter)
        
        keyword_dash_label = StyledLabel("-", size=StyledLabel.SMALL)
        keyword_dash_label.setAlignment(Qt.AlignVCenter)
        
        self.keyword_max_input = QLineEdit("60")
        self.keyword_max_input.setFixedWidth(40)  # 缩小输入框宽度
        self.keyword_max_input.setMinimumHeight(28)  # 设置最小高度
        self.keyword_max_input.setAlignment(Qt.AlignCenter)
        
        keyword_sec_label = StyledLabel("秒", size=StyledLabel.SMALL)
        keyword_sec_label.setAlignment(Qt.AlignVCenter)
        
        self.keyword_checkbox = QCheckBox("是否开启")
        self.keyword_checkbox.setChecked(True)
        self.keyword_checkbox.stateChanged.connect(self._on_keyword_enabled_changed)
        
        # 添加关键词设置到水平布局
        keyword_layout.addWidget(keyword_label)
        keyword_layout.addWidget(self.keyword_min_input)
        keyword_layout.addWidget(keyword_dash_label)
        keyword_layout.addWidget(self.keyword_max_input)
        keyword_layout.addWidget(keyword_sec_label)
        keyword_layout.addWidget(self.keyword_checkbox)
        keyword_layout.addStretch(1)
        
        # 连接输入框变化事件，更新状态栏显示
        self.keyword_min_input.textChanged.connect(self._update_keyword_status)
        self.keyword_max_input.textChanged.connect(self._update_keyword_status)
        
        parent_layout.addWidget(keyword_group)
    
    def _create_flow_welcome_config_group(self, parent_layout):
        """
        创建动态流量欢迎配置组
        
        @param parent_layout: 父布局
        """
        # 创建动态流量欢迎配置组
        flow_welcome_group = QGroupBox("动态流量欢迎配置")
        flow_welcome_layout = QVBoxLayout(flow_welcome_group)
        flow_welcome_layout.setContentsMargins(15, 15, 15, 15)
        
        # 第一行：功能开关和统计周期，以及低流量上限
        first_row = QHBoxLayout()
        first_row.setSpacing(15)
        
        # 功能开关标签和复选框
        enable_label = StyledLabel("启用:", size=StyledLabel.SMALL)
        enable_label.setAlignment(Qt.AlignVCenter)
        
        self.flow_welcome_enabled = QCheckBox()
        self.flow_welcome_enabled.setChecked(True)
        self.flow_welcome_enabled.stateChanged.connect(self._on_flow_welcome_enabled_changed)
        
        # 统计周期标签和输入框
        period_label = StyledLabel("统计周期:", size=StyledLabel.SMALL)
        period_label.setAlignment(Qt.AlignVCenter)
        
        self.flow_period_input = QLineEdit("30")
        self.flow_period_input.setFixedWidth(40)
        self.flow_period_input.setMinimumHeight(28)
        self.flow_period_input.setAlignment(Qt.AlignCenter)
        self.flow_period_input.setValidator(QIntValidator(5, 300))
        
        # 秒标签
        period_sec_label = StyledLabel("秒", size=StyledLabel.SMALL)
        period_sec_label.setAlignment(Qt.AlignVCenter)
        
        # 低流量上限标签和输入框
        low_threshold_label = StyledLabel("低流量上限:", size=StyledLabel.SMALL)
        low_threshold_label.setAlignment(Qt.AlignVCenter)
        
        self.low_flow_threshold_input = QLineEdit("10")
        self.low_flow_threshold_input.setFixedWidth(40)
        self.low_flow_threshold_input.setMinimumHeight(28)
        self.low_flow_threshold_input.setAlignment(Qt.AlignCenter)
        self.low_flow_threshold_input.setValidator(QIntValidator(1, 1000))
        
        # 人/周期标签
        low_threshold_unit_label = StyledLabel("人/周期", size=StyledLabel.SMALL)
        low_threshold_unit_label.setAlignment(Qt.AlignVCenter)
        
        # 高流量下限标签和输入框
        high_threshold_label = StyledLabel("高流量下限:", size=StyledLabel.SMALL)
        high_threshold_label.setAlignment(Qt.AlignVCenter)
        
        self.high_flow_threshold_input = QLineEdit("50")
        self.high_flow_threshold_input.setFixedWidth(40)
        self.high_flow_threshold_input.setMinimumHeight(28)
        self.high_flow_threshold_input.setAlignment(Qt.AlignCenter)
        self.high_flow_threshold_input.setValidator(QIntValidator(1, 5000))
        
        # 人/周期标签
        high_threshold_unit_label = StyledLabel("人/周期", size=StyledLabel.SMALL)
        high_threshold_unit_label.setAlignment(Qt.AlignVCenter)
        
        # 添加到第一行布局
        first_row.addWidget(enable_label)
        first_row.addWidget(self.flow_welcome_enabled)
        first_row.addWidget(period_label)
        first_row.addWidget(self.flow_period_input)
        first_row.addWidget(period_sec_label)
        first_row.addSpacing(10)
        first_row.addWidget(low_threshold_label)
        first_row.addWidget(self.low_flow_threshold_input)
        first_row.addWidget(low_threshold_unit_label)
        first_row.addSpacing(10)
        first_row.addWidget(high_threshold_label)
        first_row.addWidget(self.high_flow_threshold_input)
        first_row.addWidget(high_threshold_unit_label)
        first_row.addStretch(1)
        
        # 第二行：欢迎策略设置（中流量随机比例和触发阈值）
        strategy_row = QHBoxLayout()
        strategy_row.setSpacing(15)
        
        # 中流量随机比例标签
        random_ratio_label = StyledLabel("中流量随机比例:", size=StyledLabel.SMALL)
        random_ratio_label.setAlignment(Qt.AlignVCenter)
        
        # 中流量随机比例滑块
        self.medium_flow_ratio_slider = QSlider(Qt.Horizontal)
        self.medium_flow_ratio_slider.setRange(1, 100)
        self.medium_flow_ratio_slider.setValue(30)
        self.medium_flow_ratio_slider.setFixedHeight(20)
        
        # 中流量随机比例值
        self.medium_flow_ratio_value = StyledLabel("30%", size=StyledLabel.SMALL)
        self.medium_flow_ratio_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.medium_flow_ratio_value.setFixedWidth(40)
        
        # 连接滑块值变化信号
        self.medium_flow_ratio_slider.valueChanged.connect(self._on_medium_flow_ratio_changed)
        
        # 触发阈值标签
        trigger_label = StyledLabel("触发检测阈值:", size=StyledLabel.SMALL)
        trigger_label.setAlignment(Qt.AlignVCenter)
        
        # 触发阈值滑块
        self.trigger_ratio_slider = QSlider(Qt.Horizontal)
        self.trigger_ratio_slider.setRange(10, 100)
        self.trigger_ratio_slider.setValue(50)  # 默认50%
        self.trigger_ratio_slider.setFixedHeight(20)
        
        # 触发阈值值
        self.trigger_ratio_value = StyledLabel("50%", size=StyledLabel.SMALL)
        self.trigger_ratio_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.trigger_ratio_value.setFixedWidth(40)
        
        # 连接滑块值变化信号
        self.trigger_ratio_slider.valueChanged.connect(self._on_trigger_ratio_changed)
        
        # 添加到策略行布局
        strategy_row.addWidget(random_ratio_label)
        strategy_row.addWidget(self.medium_flow_ratio_slider)
        strategy_row.addWidget(self.medium_flow_ratio_value)
        strategy_row.addSpacing(10)
        strategy_row.addWidget(trigger_label)
        strategy_row.addWidget(self.trigger_ratio_slider)
        strategy_row.addWidget(self.trigger_ratio_value)
        
        # 添加输入框变化事件处理
        self.flow_period_input.textChanged.connect(self._update_flow_welcome_config)
        self.low_flow_threshold_input.textChanged.connect(self._update_flow_welcome_config)
        self.high_flow_threshold_input.textChanged.connect(self._update_flow_welcome_config)
        
        # 添加到主布局
        flow_welcome_layout.addLayout(first_row)
        flow_welcome_layout.addLayout(strategy_row)
        
        parent_layout.addWidget(flow_welcome_group)
    
    def _on_ai_config_updated(self, config_name, value):
        """
        处理AI配置更新事件
        
        @param config_name: 配置项名称
        @param value: 配置项值
        """
        # 转发信号
        self.config_updated.emit(config_name, value)
    
    def _on_speech_updated(self, config_name, value):
        """
        处理话术更新事件
        
        @param config_name: 配置项名称
        @param value: 配置项值
        """
        # 转发信号
        self.config_updated.emit(config_name, value)

    def _update_audio_output_status(self, value):
        """
        更新音频输出状态
        
        @param value: 音频输出设备名称
        """
        # 使用完整的设备名称，不进行截断
        device_name = value
        
        self.logger.info(f"音频输出设备已更改为: {device_name}")
        
        # 获取设备详细信息
        device_info = None
        for i in range(self.audio_output_combo.count()):
            if self.audio_output_combo.itemText(i) == value:
                device_info = self.audio_output_combo.itemData(i, Qt.UserRole)
                break
        
        # 直接保存到配置服务
        config_service = ServiceLocator.get(IConfigService)
        if config_service:
            # 保存设备名称
            config_service.set("audio.output", device_name)
            self.logger.info(f"已保存音频输出设备到配置: {device_name}")
            
            # 保存设备详细信息
            if device_info:
                config_service.set("audio.output_info", device_info)
                self.logger.info("已保存音频设备详细信息到配置")
        
        # 重要：立即应用设置到AudioService
        audio_service = ServiceLocator.get(IAudioService)
        if audio_service:
            try:
                audio_service.set_output_device(device_name)
                self.logger.info(f"已立即应用音频输出设备: {device_name}")
            except Exception as e:
                self.logger.error(f"应用音频输出设备失败: {str(e)}")
        else:
            self.logger.warning("无法获取音频服务，设备设置将在下次启动时生效")
    
    def _update_keyword_status(self):
        """
        更新关键词状态
        """
        try:
            min_value = int(self.keyword_min_input.text())
            max_value = int(self.keyword_max_input.text())
            status = f"{min_value}-{max_value}秒"
            self.config_updated.emit("keyword_status", status)
            
            # 发送具体的配置更新信号
            self.config_updated.emit("keyword_min", min_value)
            self.config_updated.emit("keyword_max", max_value)
        except ValueError:
            pass
    
    def _on_volume_changed(self, value):
        """
        音量改变事件处理
        
        @param value: 音量值（0-100）
        """
        # 更新音量值显示
        self.volume_value.setText(str(value))
        
        # 将音量值转换为 0-1 范围
        volume = value / 100.0
        
        # 发送音量更新信号
        self.config_updated.emit("audio_volume", volume)
    
    def set_keyword_user_config(self, keyword_min, keyword_max, keyword_enabled=True):
        """
        设置关键词配置
        """
        # 设置关键词时间范围
        self.keyword_min_input.setText(str(keyword_min))
        self.keyword_max_input.setText(str(keyword_max))
        
        # 设置关键词开关
        self.keyword_checkbox.setChecked(keyword_enabled)
    
    def set_config_path(self, path):
        """
        设置配置路径
        
        @param path: 配置路径
        """
        self.logger.info(f"设置配置路径: {path}")
        
        # 检查路径是否为空
        if not path:
            self.logger.warning("配置路径为空")
            return
            
        # 检查路径是否存在
        if not os.path.exists(path):
            self.logger.warning(f"配置路径不存在: {path}")
            try:
                os.makedirs(path, exist_ok=True)
                self.logger.info(f"已创建配置路径: {path}")
            except Exception as e:
                self.logger.error(f"创建配置路径失败: {str(e)}")
                return
        
        # 保存配置路径
        self.config_path = path
        
        # 更新配置路径输入框
        if self.config_path_input:
            self.config_path_input.setText(path)
        
        # 通知话术模块更新配置路径
        if self.speech_module:
            self.speech_module.set_config_path(path)
        
        # 通知音色管理模块更新配置路径
        if self.voice_module:
            self.voice_module.set_config_path(path)

    def _on_host_speed_changed(self, value):
        """
        主播语速改变事件处理
        
        @param value: 语速值（30-200，对应0.3-2.0）
        """
        # 计算实际语速值（0.3-2.0）
        actual_speed = value / 100.0
        
        # 更新语速值显示，保留两位小数
        self.host_speed_value.setText(f"{actual_speed:.2f}")
        
        # 发送语速更新信号
        self.config_updated.emit("host_speed", value)
    
    def _on_assist_speed_changed(self, value):
        """
        助播语速改变事件处理
        
        @param value: 语速值（30-200，对应0.3-2.0）
        """
        # 计算实际语速值（0.3-2.0）
        actual_speed = value / 100.0
        
        # 更新语速值显示，保留两位小数
        self.assist_speed_value.setText(f"{actual_speed:.2f}")
        
        # 发送语速更新信号
        self.config_updated.emit("assist_speed", value)

    def _on_keyword_enabled_changed(self, state):
        """
        关键词开关状态改变事件处理
        
        @param state: 开关状态
        """
        enabled = state == Qt.Checked
        self.config_updated.emit("keyword_enabled", enabled)
    
    def _on_flow_welcome_enabled_changed(self, state):
        """
        流量欢迎功能开关状态改变事件处理
        
        @param state: 开关状态
        """
        enabled = state == Qt.Checked
        self.config_updated.emit("flow_welcome.enabled", enabled)
        self.logger.info(f"动态流量欢迎功能已{'启用' if enabled else '禁用'}")

    def _on_medium_flow_ratio_changed(self, value):
        """
        中流量随机比例变化处理
        
        @param value: 滑块值(1-100)
        """
        # 更新显示
        self.medium_flow_ratio_value.setText(f"{value}%")
        
        # 保存配置
        ratio = value / 100.0
        self.config_updated.emit("flow_welcome.medium_flow_ratio", ratio)
        self.logger.debug(f"中流量随机比例已更新为: {ratio:.2f}")

    def _on_trigger_ratio_changed(self, value):
        """
        触发阈值比例变化处理
        
        @param value: 滑块值(10-100)
        """
        # 更新显示
        self.trigger_ratio_value.setText(f"{value}%")
        
        # 保存配置
        ratio = value / 100.0
        self.config_updated.emit("flow_welcome.trigger_ratio", ratio)
        self.logger.debug(f"触发检测阈值已更新为: {ratio:.2f}")

    def _update_flow_welcome_config(self):
        """
        更新流量欢迎配置
        """
        try:
            # 获取统计周期
            period = int(self.flow_period_input.text())
            self.config_updated.emit("flow_welcome.period", period)
            
            # 获取低流量阈值
            low_threshold = int(self.low_flow_threshold_input.text())
            self.config_updated.emit("flow_welcome.low_threshold", low_threshold)
            
            # 获取高流量阈值
            high_threshold = int(self.high_flow_threshold_input.text())
            self.config_updated.emit("flow_welcome.high_threshold", high_threshold)
            
            self.logger.debug(f"流量欢迎配置已更新: 周期={period}秒, 低流量上限={low_threshold}, 高流量下限={high_threshold}")
        except ValueError:
            self.logger.warning("流量欢迎配置更新失败，请检查输入值")

    def set_speech_config(self, config):
        """
        设置语音配置
        
        @param config: 语音配置字典
        """
        if not config:
            return
        
        # 设置主播语速
        host_speed = config.get("host_speed", 80)  # 默认0.8
        self.host_speed_slider.setValue(host_speed)
        self.host_speed_value.setText(f"{host_speed/100:.2f}")
        
        # 设置助播语速
        assist_speed = config.get("assist_speed", 100)  # 默认1.0
        self.assist_speed_slider.setValue(assist_speed)
        self.assist_speed_value.setText(f"{assist_speed/100:.2f}")
        
        # 设置音色配置
        if self.voice_module:
            # 先设置配置路径，确保音色选项已加载
            if hasattr(self, 'config_path') and self.config_path:
                self.voice_module.set_config_path(self.config_path)
                
            # 设置音色配置
            self.voice_module.set_voice_config(config)
        
        # 手动触发语速配置更新信号，确保配置被保存
        self.config_updated.emit("host_speed", host_speed)
        self.config_updated.emit("assist_speed", assist_speed)

    def set_audio_config(self, config):
        """
        设置音频配置
        
        @param config: 音频配置字典
        """
        self.logger.info(f"设置音频配置: {config}")
        
        # 记录当前可用的音频输出设备
        available_outputs = [self.audio_output_combo.itemText(i) for i in range(self.audio_output_combo.count())]
        self.logger.info(f"当前可用的音频输出设备: {available_outputs}")
        
        # 设置音频输出
        output = config.get("audio", {}).get("output", "默认设备")
        self.logger.info(f"从配置中获取的音频输出设备: {output}")
        
        # 检查设备是否在列表中
        index = self.audio_output_combo.findText(output)
        if index >= 0:
            self.audio_output_combo.setCurrentIndex(index)
            self.logger.info(f"已设置音频输出: {output}, 索引: {index}")
        else:
            # 如果设备不在列表中，使用默认设备
            self.logger.warning(f"配置的音频设备 '{output}' 不在可用设备列表中，使用默认设备")
            self.audio_output_combo.setCurrentIndex(0)  # 默认设备的索引为0
        
        # 设置音量
        volume = config.get("volume", 1.0)
        # 确保音量值是整数，如果是浮点数(0-1范围)，则转换为整数(0-100范围)
        if isinstance(volume, float) and volume <= 1.0:
            volume = int(volume * 100)
        else:
            volume = int(volume)  # 确保是整数类型
        self.logger.info(f"设置音量: {volume} ({volume}%)")
        # 断开信号连接，避免触发不必要的更新
        self.volume_slider.blockSignals(True)
        self.volume_slider.setValue(volume)
        self.volume_slider.blockSignals(False)
        self.volume_value.setText(str(volume))
        
        # 手动触发配置更新信号，确保配置被保存
        if output:
            self.config_updated.emit("audio_output", output)
        if volume is not None:
            self.config_updated.emit("audio_volume", volume)

    def update_bot_list(self, bots):
        """
        更新机器人列表
        
        @param bots: 机器人列表
        """
        if self.ai_config_module:
            self.ai_config_module.update_bot_list(bots)
    
    def set_ai_config(self, ai_config):
        """
        设置AI配置
        
        @param ai_config: AI配置字典
        """
        # 暂时断开信号连接，避免触发多次配置更新
        if self.ai_config_module:
            try:
                # 断开信号连接
                self.ai_config_module.ai_config_updated.disconnect()
                self.logger.info("已断开AI配置模块的信号连接")
            except Exception as e:
                self.logger.warning(f"断开AI配置模块信号连接失败: {str(e)}")
            
            # 设置配置
            if "token" in ai_config:
                self.ai_config_module.set_token(ai_config["token"])
            
            if "bot_id" in ai_config and "last_bot_name" in ai_config:
                self.ai_config_module.set_bot(ai_config["bot_id"], ai_config["last_bot_name"])
            
            if "stream_mode" in ai_config:
                self.ai_config_module.set_stream_mode(ai_config["stream_mode"])
            
            try:
                # 重新连接信号
                self.ai_config_module.ai_config_updated.connect(self._on_ai_config_updated)
                self.logger.info("已重新连接AI配置模块的信号")
            except Exception as e:
                self.logger.error(f"重新连接AI配置模块信号失败: {str(e)}")

    def _on_browse_clicked(self):
        """
        浏览按钮点击事件处理
        """
        # 打开文件夹选择对话框
        folder_path = QFileDialog.getExistingDirectory(self, "选择配置路径")
        if folder_path:
            self.config_path_input.setText(folder_path)
            # 发送配置更新信号
            self.config_updated.emit("config_path", folder_path)
            self.logger.info(f"已选择配置路径: {folder_path}")
    
    def _on_refresh_config_clicked(self):
        """
        刷新配置按钮点击事件处理
        """
        path = self.config_path_input.text().strip()
        if not path:
            QMessageBox.warning(self, "警告", "请先输入配置路径")
            return
            
        # 通知话术模块更新配置路径
        if self.speech_module:
            self.speech_module.set_config_path(path)
            
        # 通知音色管理模块更新配置路径
        if self.voice_module:
            self.voice_module.set_config_path(path)
            
        # 发送配置更新信号
        self.config_updated.emit("refresh_config", path)
        self.logger.info(f"刷新配置: {path}")
        
        # 显示成功提示
        show_toast(self, "配置已刷新", 2000, Toast.SUCCESS)

    def _load_voice_options(self):
        """
        重新加载音色选项
        """
        # 如果音色管理模块存在，调用其加载方法
        if self.voice_module:
            self.voice_module._load_voice_options()
            
        # 如果语音配置模块存在，也需要刷新
        if self.speech_module:
            self.speech_module._load_speech_types()

    def _load_audio_devices(self):
        """
        加载音频设备列表
        """
        try:
            # 清空现有项
            self.audio_output_combo.clear()
            
            # 获取音频服务
            audio_service = ServiceLocator.get(IAudioService)
            
            if not audio_service:
                self.logger.warning("无法获取音频服务，使用默认设备")
                # 只添加默认设备
                self.audio_output_combo.addItem("默认设备")
                self.audio_output_combo.setItemData(0, {"id": "default", "name": "默认设备"}, Qt.UserRole)
                return
            
            # 通过音频服务获取设备列表
            try:
                # 检查是否有get_output_devices方法
                if hasattr(audio_service, 'get_output_devices'):
                    # 获取设备列表
                    device_names = audio_service.get_output_devices()
                    self.logger.info(f"从音频服务获取到 {len(device_names)} 个音频设备")
                    
                    # 添加所有设备到下拉框
                    for i, device_name in enumerate(device_names):
                        self.logger.debug(f"添加音频设备: [{i}] {device_name}")
                        index = self.audio_output_combo.count()
                        self.audio_output_combo.addItem(device_name)
                        self.audio_output_combo.setItemData(index, {"id": device_name, "name": device_name}, Qt.UserRole)
                    
                    self.logger.info(f"已加载 {self.audio_output_combo.count()} 个音频输出设备")
                else:
                    self.logger.warning("音频服务不支持get_output_devices方法")
                    # 添加默认设备
                    self.audio_output_combo.addItem("默认设备")
                    self.audio_output_combo.setItemData(0, {"id": "default", "name": "默认设备"}, Qt.UserRole)
                
                # 确保至少有"默认设备"选项
                if self.audio_output_combo.count() == 0:
                    self.logger.warning("未找到音频设备，添加默认设备")
                    self.audio_output_combo.addItem("默认设备")
                    self.audio_output_combo.setItemData(0, {"id": "default", "name": "默认设备"}, Qt.UserRole)
                
                # 从配置中获取并设置当前选择的设备
                self._set_current_device_from_config()
                
            except Exception as e:
                self.logger.error(f"从音频服务获取设备失败: {str(e)}")
                import traceback
                self.logger.error(traceback.format_exc())
                
                # 出错时只添加默认设备
                self.audio_output_combo.clear()
                self.audio_output_combo.addItem("默认设备")
                self.audio_output_combo.setItemData(0, {"id": "default", "name": "默认设备"}, Qt.UserRole)
            
        except Exception as e:
            self.logger.error(f"加载音频设备失败: {str(e)}")
            import traceback
            self.logger.error(traceback.format_exc())
            
            # 出错时只添加默认设备
            self.audio_output_combo.clear()
            self.audio_output_combo.addItem("默认设备")
            self.audio_output_combo.setItemData(0, {"id": "default", "name": "默认设备"}, Qt.UserRole)
    
    def _set_current_device_from_config(self):
        """
        从配置中获取并设置当前音频设备
        """
        try:
            # 获取配置服务
            config_service = ServiceLocator.get(IConfigService)
            if not config_service:
                self.logger.warning("无法获取配置服务，使用默认设备")
                self.audio_output_combo.setCurrentIndex(0)  # 默认设备
                return
                
            # 从配置中获取当前设备
            current_device = config_service.get("audio.output", "默认设备")
            self.logger.info(f"从配置中获取的音频输出设备: {current_device}")
            
            # 查找设备在下拉框中的位置
            index = self.audio_output_combo.findText(current_device)
            if index >= 0:
                self.audio_output_combo.setCurrentIndex(index)
                self.logger.info(f"已选择音频设备: {current_device} (索引 {index})")
            else:
                # 如果未找到，尝试模糊匹配
                best_match = -1
                best_score = 0
                for i in range(self.audio_output_combo.count()):
                    combo_text = self.audio_output_combo.itemText(i)
                    if current_device in combo_text or combo_text in current_device:
                        # 计算匹配度，简单使用字符串长度作为权重
                        score = len(set(current_device) & set(combo_text))
                        if score > best_score:
                            best_score = score
                            best_match = i
                
                if best_match >= 0:
                    self.audio_output_combo.setCurrentIndex(best_match)
                    match_text = self.audio_output_combo.itemText(best_match)
                    self.logger.info(f"通过模糊匹配选择音频设备: {match_text} (匹配 '{current_device}')")
                else:
                    # 无匹配，使用默认设备
                    self.logger.warning(f"配置的音频设备 '{current_device}' 不在可用设备列表中，使用默认设备")
                    self.audio_output_combo.setCurrentIndex(0)  # 默认设备
        except Exception as e:
            self.logger.error(f"设置当前设备失败: {str(e)}")
            self.audio_output_combo.setCurrentIndex(0)  # 默认设备

    def _update_speech_interval_status(self):
        """
        更新话术间隔状态
        """
        try:
            min_value = int(self.speech_interval_min_input.text())
            max_value = int(self.speech_interval_max_input.text())
            
            # 确保最小值不大于最大值
            if min_value > max_value:
                # 交换两个值
                self.speech_interval_min_input.blockSignals(True)
                self.speech_interval_max_input.blockSignals(True)
                self.speech_interval_min_input.setText(str(max_value))
                self.speech_interval_max_input.setText(str(min_value))
                self.speech_interval_min_input.blockSignals(False)
                self.speech_interval_max_input.blockSignals(False)
                min_value, max_value = max_value, min_value
            
            status = f"{min_value}-{max_value}毫秒"
            self.config_updated.emit("speech_interval_status", status)
            
            # 发送具体的配置更新信号
            self.config_updated.emit("speech_interval_min", min_value)
            self.config_updated.emit("speech_interval_max", max_value)
            
            # 保存到配置服务
            config_service = ServiceLocator.get(IConfigService)
            if config_service:
                config_service.set("speech_interval_min", min_value)
                config_service.set("speech_interval_max", max_value)
                
                # 直接更新音频服务的配置
                audio_service = ServiceLocator.get(IAudioService)
                if audio_service:
                    # 创建包含话术间隔时间的配置字典
                    interval_config = {
                        "speech_interval_min": min_value,
                        "speech_interval_max": max_value
                    }
                    # 调用音频服务的configure方法更新配置
                    audio_service.configure(interval_config)
                    self.logger.info(f"已更新音频服务的话术间隔时间配置：{min_value}-{max_value}毫秒")
                
        except ValueError:
            pass

    def load_config(self):
        """
        从配置服务加载配置
        """
        # 获取配置服务
        config_service = ServiceLocator.get(IConfigService)
        if not config_service:
          self.logger.warning("无法获取配置服务，无法加载配置")
          return
        
        # 加载配置路径
        config_path = config_service.get("app.config_path", "")
        if config_path:
            self.config_path_input.setText(config_path)
            self.config_path = config_path
            
            # 加载话术来源列表
            self._load_speech_sources()
            
            # 设置当前选中的话术来源
            speech_source = config_service.get("app.speech_source", "主话术")
            self.logger.info(f"从配置服务加载话术来源: {speech_source}")
            
            if speech_source:
                index = self.speech_source_combo.findText(speech_source)
                if index >= 0:
                    self.speech_source_combo.setCurrentIndex(index)
                    self.logger.info(f"已设置当前话术来源: {speech_source}")
                else:
                    self.logger.warning(f"找不到话术来源: {speech_source}，使用默认选择")
        
        # 加载关键词设置
        keyword_min = config_service.get("keyword.min", 30)
        keyword_max = config_service.get("keyword.max", 60)
        keyword_enabled = config_service.get("keyword.enabled", True)
        self.keyword_min_input.setText(str(keyword_min))
        self.keyword_max_input.setText(str(keyword_max))
        self.keyword_checkbox.setChecked(keyword_enabled)
        
        # 加载流量欢迎设置
        flow_welcome_enabled = config_service.get("flow_welcome.enabled", True)
        flow_period = config_service.get("flow_welcome.period", 30)
        low_threshold = config_service.get("flow_welcome.low_threshold", 10)
        high_threshold = config_service.get("flow_welcome.high_threshold", 50)
        medium_flow_ratio = config_service.get("flow_welcome.medium_flow_ratio", 0.3)
        trigger_ratio = config_service.get("flow_welcome.trigger_ratio", 0.5)
        
        self.flow_welcome_enabled.setChecked(flow_welcome_enabled)
        self.flow_period_input.setText(str(flow_period))
        self.low_flow_threshold_input.setText(str(low_threshold))
        self.high_flow_threshold_input.setText(str(high_threshold))
        
        medium_ratio_percent = int(medium_flow_ratio * 100)
        trigger_ratio_percent = int(trigger_ratio * 100)
        self.medium_flow_ratio_slider.setValue(medium_ratio_percent)
        self.trigger_ratio_slider.setValue(trigger_ratio_percent)
        
        # 加载音频输出设备
        audio_output = config_service.get("audio.output", "")
        if audio_output:
            # 查找并设置音频输出设备
            for i in range(self.audio_output_combo.count()):
                if self.audio_output_combo.itemText(i) == audio_output:
                    self.audio_output_combo.setCurrentIndex(i)
                    break
        
        # 加载音量设置
        volume = config_service.get("audio.volume", 80)
        # 确保音量值是整数，如果是浮点数(0-1范围)，则转换为整数(0-100范围)
        if isinstance(volume, float) and volume <= 1.0:
            volume = int(volume * 100)
        else:
            volume = int(volume)  # 确保是整数类型
        self.volume_slider.setValue(volume)
        
        # 加载语速设置
        host_speed = config_service.get("speech.host_speed", 80)
        assist_speed = config_service.get("speech.assist_speed", 100)
        
        self.host_speed_slider.setValue(host_speed)
        self.assist_speed_slider.setValue(assist_speed)
        
        # 加载话术间隔设置
        speech_interval_min = config_service.get("speech.interval_min", 100)
        speech_interval_max = config_service.get("speech.interval_max", 1000)
        
        self.speech_interval_min_input.setText(str(speech_interval_min))
        self.speech_interval_max_input.setText(str(speech_interval_max))
        
        # 加载音频空白处理设置
        audio_trim_enabled = config_service.get("audio.trim_enabled", True)
        audio_trim_threshold = config_service.get("audio.trim_threshold", 0.02)
        
        self.audio_trim_enabled.setChecked(audio_trim_enabled)
        
        # 将阈值转换为滑块值（0.01-0.05 => 10-50）
        threshold_value = int(audio_trim_threshold * 1000)
        self.audio_trim_threshold_slider.setValue(threshold_value)

    def _update_audio_trim_status(self, state):
        """
        更新音频空白处理状态
        
        @param state: 状态
        """
        enabled = state == Qt.Checked
        self.config_updated.emit("audio_trim_enabled", enabled)
        
        # 保存到配置服务
        config_service = ServiceLocator.get(IConfigService)
        if config_service:
            config_service.set("audio.trim_enabled", enabled)
            
            # 获取当前的阈值
            threshold = float(self.audio_trim_threshold_value.text())
            
            # 创建包含音频空白处理配置的字典
            trim_config = {
                "trim_enabled": enabled,
                "trim_threshold": threshold
            }
            
            # 直接更新音频服务的配置
            audio_service = ServiceLocator.get(IAudioService)
            if audio_service:
                audio_service.configure(trim_config)
                self.logger.info(f"已更新音频服务的空白处理配置：启用={enabled}，阈值={threshold}")
    
    def _on_audio_trim_threshold_changed(self, value):
        """
        音频空白处理灵敏度改变事件处理
        
        @param value: 灵敏度值
        """
        # 更新灵敏度值显示
        threshold = value / 1000.0
        self.audio_trim_threshold_value.setText(f"{threshold:.2f}")
        
        # 发送灵敏度更新信号
        self.config_updated.emit("audio_trim_threshold", threshold)
        
        # 保存到配置服务
        config_service = ServiceLocator.get(IConfigService)
        if config_service:
            config_service.set("audio.trim_threshold", threshold)
            
            # 获取当前的启用状态
            enabled = self.audio_trim_enabled.isChecked()
            
            # 创建包含音频空白处理配置的字典
            trim_config = {
                "trim_enabled": enabled,
                "trim_threshold": threshold
            }
            
            # 直接更新音频服务的配置
            audio_service = ServiceLocator.get(IAudioService)
            if audio_service:
                audio_service.configure(trim_config)
                self.logger.info(f"已更新音频服务的空白处理配置：启用={enabled}，阈值={threshold}")

    def _load_speech_sources(self):
        """
        加载话术来源列表
        """
        try:
            # 获取配置路径
            if not self.config_path:
                self.logger.warning("配置路径未设置，无法加载话术来源")
                return
            
            # 构建话术管理目录路径
            speech_dir = os.path.join(self.config_path, "话术管理")
            
            # 检查目录是否存在
            if not os.path.exists(speech_dir):
                self.logger.warning(f"话术管理目录不存在: {speech_dir}")
                return
            
            # 获取所有子目录
            subdirs = [d for d in os.listdir(speech_dir) 
                      if os.path.isdir(os.path.join(speech_dir, d))]
            
            # 保存当前选中的项
            current_source = self.speech_source_combo.currentText()
            
            # 清空并重新添加
            self.speech_source_combo.clear()
            for subdir in subdirs:
                self.speech_source_combo.addItem(subdir)
            
            # 恢复之前选中的项
            if current_source and current_source in subdirs:
                index = self.speech_source_combo.findText(current_source)
                if index >= 0:
                    self.speech_source_combo.setCurrentIndex(index)
            elif self.speech_source_combo.count() > 0:
                # 如果没有之前选中的项，默认选择第一个
                self.speech_source_combo.setCurrentIndex(0)
            
            self.logger.info(f"已加载 {len(subdirs)} 个话术来源")
        except Exception as e:
            self.logger.error(f"加载话术来源失败: {str(e)}")

    def _on_speech_source_changed(self, source):
        """
        话术来源改变事件处理
        
        @param source: 选中的话术来源
        """
        try:
            if not source:
                return
            
            self.logger.info(f"切换话术来源: {source}")
            
            # 获取配置服务
            config_service = ServiceLocator.get(IConfigService)
            if config_service:
                # 保存到配置
                config_service.set("app.speech_source", source)
                config_service.save_config()
                
                # 获取音频服务并更新话术来源
                audio_service = ServiceLocator.get(IAudioService)
                if audio_service and audio_service.main_speech_manager:
                    audio_service.main_speech_manager.set_speech_source(source)
                    self.logger.info(f"已更新主话术管理器的话术来源: {source}")
                    
                    # 重新加载主话术
                    audio_service.main_speech_manager.reload()
                    self.logger.info("已重新加载主话术")
            
            # 发送配置更新信号
            self.config_updated.emit("speech_source", source)
            
        except Exception as e:
            self.logger.error(f"切换话术来源失败: {str(e)}")